package com.bit.blog.common.advice;

import com.bit.blog.common.exception.BlogException;
import com.bit.blog.pojo.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.ArrayList;
import java.util.List;

@ResponseBody
@Slf4j
@ControllerAdvice
public class ExceptionAdvice {
    @ExceptionHandler
    public Result error(Exception e){
        log.error("发生异常, e:", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler
    public Result error(BlogException e){
        log.error("发生异常, e:", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler
    public Result error(HandlerMethodValidationException e){
        log.error("发生异常, e:", e);
        List<String> errors = new ArrayList<>();
        e.getAllErrors().forEach(error ->
                errors.add(error.getDefaultMessage()));
        return Result.error(errors.toString());
    }

//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler
    public Result error(MethodArgumentNotValidException e){
        log.error("发生异常, e:", e);
        return Result.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }



}
